package com.coffee.socketio.handler;

import com.coffee.core.JSONUtils;
import com.coffee.socketio.command.CommandModelMapping;
import com.coffee.socketio.command.CommandModel;
import com.coffee.socketio.command.TextCommand;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DataListener;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @author songkui
 * @since 2024/3/16 17:46
 */
@NoArgsConstructor
@Slf4j
public class TextListener implements DataListener<String> {

    private String key;
    private String event;

    public TextListener(String namespace, String event){
        this.key = Optional.ofNullable(namespace).orElse("")+event;
        this.event = event;
    }


    @Override
    public void onData(SocketIOClient client, String data, AckRequest ackSender) throws Exception {
        CommandModel commandModel = CommandModelMapping.getSocketCommandModel(key);
        //2, 业务校验
        if (commandModel.isVerifyType()){
            if (HandlerMapping.getSocketUserValidHandler() != null &&  HandlerMapping.getSocketUserValidHandler().verifyInvalid(client)) {
                client.disconnect();
                return;
            }
        }

        SocketioTextHandler handler = HandlerMapping.getSocketHandler(event);
        if (null == handler){
            log.error("On message not mapping handler {}", data);
            client.disconnect();
            return;
        }

        TextCommand command = new TextCommand();
        command.setEvent(event);
        command.setClient(client);
        command.setSessionId(client.getSessionId().toString());
        command.setRequest(Optional.ofNullable(data).map(s -> JSONUtils.parse(data, commandModel.getTextRequest().getClass()) ).orElse(null));

        handler.handle(command);

    }
}
